import env from '/@/ossutils/config.ts';
import base64 from '/@/ossutils/common/base64.js';
import Crypto from '/@/ossutils/common/crypto.js';
import hmac from '/@/ossutils/common/hmac.js';
import sha from '/@/ossutils/common/sha1.js';
import { ElLoading, ElMessage } from 'element-plus';
import AliOss from 'ali-oss';
import { nextTick } from 'vue';
const errorMessage = ['图片错误', '视频错误', '文件错误'];
let fileResult = []; //返回图片数据
// 上传图片前校验 type:上传类型;0-图片,1-视频,filePath:图片数据,dir:buket桶文件夹,name:图片名称
const uploadFileFormat = (type, filePath, dir) => {
	return new Promise((resolve, reject) => {
		try {
			if (!filePath || filePath.length === 0) {
				ElMessage({
					message: errorMessage[type],
					type: 'error',
				});
				reject();
			}
			const loadingInstance = ElLoading.service({
				text: `正在上传...`,
				background: 'rgba(122, 122, 122, 0.8)',
			});

			const policyBase64 = getPolicyBase64();
			const signature = getSignature(policyBase64); //获取签名

			let config = {
				url: env.uploadImageUrl,
				OSSAccessKeyId: env.OSSAccessKeyId,
				accessKeySecret: env.AccessKeySecret,
				policy: policyBase64,
				signature: signature,
				success_action_status: '200',
				region: env.region, // 服务器集群地区
				bucket: env.bucket,
				secure: env.secure,
			};
			//先把需要上传的参数转一下格式
			let uploadFiles = Array.isArray(filePath) ? filePath : [filePath];
			let uploadTask = [];
			let ossClient = new AliOss({
				accessKeyId: config.OSSAccessKeyId,
				accessKeySecret: config.accessKeySecret,
				bucket: config.bucket,
				region: config.region,
				secure: config.secure,
			});

			uploadFiles.forEach((task) => {
				uploadTask.push(
					new Promise((resolve) => {
						if (typeof task === 'string' && task.indexOf(import.meta.env.VITE_UPLOAD_KEY) > -1) {
							//如果已经是上传过的
							console.log('已经上传过');
							resolve(task);
						} else {
							console.log(task, '上传的文件');
							if (type < 2) {
								//文件名 采用当前的时间戳 + 150内的随机数来给图片命名
								const date = new Date().format('yyyyMMdd'); // 当前时间
								const dateTime = new Date().format('hhmmss'); // 当前时间
								const randomStr = Math.floor(Math.random() * 150); //  4位随机字符串
								ossClient
									.multipartUpload(dir + '/' + date + '/' + dateTime + randomStr + '' + ['.jpg', '.mp4'][type], task)
									.then(({ res }) => {
										console.log(res, '上传成功');
										if (type === 0) {
											resolve(res.requestUrls[0].indexOf('?uploadId=') > -1 ? res.requestUrls[0].substr(0, res.requestUrls[0].indexOf('?uploadId=')) : res.requestUrls[0]);
										} else {

											resolve(res.requestUrls[0].indexOf('?uploadId=') > -1 ? res.requestUrls[0].substr(0, res.requestUrls[0].indexOf('?uploadId=')) : res.requestUrls[0]);
										}
									})
									.catch((error) => {
										console.log(error);
										nextTick(() => {
											loadingInstance.close();
										});
									});
							} else {
								const date = new Date().format('yyyyMMdd'); // 当前时间
								const dateTime = new Date().format('hhmmss'); // 当前时间
								const randomStr = Math.floor(Math.random() * 150); //  4位随机字符串
								ossClient
									.multipartUpload(dir + '/' + date + '/' + dateTime + '/' + task.name, task)
									.then(({ res }) => {
										console.log(res, '上传成功');
										resolve(res.requestUrls[0].indexOf('?uploadId=') > -1 ? res.requestUrls[0].substr(0, res.requestUrls[0].indexOf('?uploadId=')) : res.requestUrls[0]);
									})
									.catch((error) => {
										console.log(error);
										nextTick(() => {
											loadingInstance.close();
										});
									});
							}
						}
					})
				);
			});
			Promise.all(uploadTask).then((result) => {
				console.log(result);
				resolve(result);
				nextTick(() => {
					loadingInstance.close();
				});
			}).catch(() => {
				ElMessage.warning('上传失败')
				nextTick(() => {
					loadingInstance.close();
				});
			})
		} catch (error) {
			reject(error);
		}
	});
};

const getPolicyBase64 = function () {
	let date = new Date();
	// date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		expiration: srcT, //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
		conditions: [
			['content-length-range', 0, 100 * 1024 * 1024], // 设置上传文件的大小限制,100mb
		],
	};

	const policyBase64 = base64.encode(JSON.stringify(policyText));
	console.log(policyBase64);
	return policyBase64;
};

const getSignature = function (policyBase64) {
	const accesskey = env.AccessKeySecret;
	// const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
	//   asBytes: true
	// });
	const bytes = Crypto.Crypto.HMAC(Crypto.Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true,
	});
	const signature = Crypto.Crypto.util.bytesToBase64(bytes);
	return signature;
};

Date.prototype.format = function (fmt) {
	var o = {
		'M+': this.getMonth() + 1, //月份
		'd+': this.getDate(), //日
		'h+': this.getHours(), //小时
		'm+': this.getMinutes(), //分
		's+': this.getSeconds(), //秒
		'q+': Math.floor((this.getMonth() + 3) / 3), //季度
		S: this.getMilliseconds(), //毫秒
	};

	if (/(y+)/.test(fmt)) {
		fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
	}

	for (var k in o) {
		if (new RegExp('(' + k + ')').test(fmt)) {
			fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length));
		}
	}

	return fmt;
};
export default uploadFileFormat;
